package net.lab1024.smartadmin.module.weapp.orders.service;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaSubscribeMessage;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import me.chanjar.weixin.common.error.WxErrorException;
import net.lab1024.smartadmin.common.constant.ResponseCodeConst;
import net.lab1024.smartadmin.common.domain.PageResultDTO;
import net.lab1024.smartadmin.common.domain.ResponseDTO;
import net.lab1024.smartadmin.common.weixin.AddToMessageQueue;
import net.lab1024.smartadmin.common.weixin.WxMaConfiguration;
import net.lab1024.smartadmin.module.support.file.constant.FileServiceTypeEnum;
import net.lab1024.smartadmin.module.support.file.service.FileService;
import net.lab1024.smartadmin.module.support.idgenerator.IdGeneratorService;
import net.lab1024.smartadmin.module.support.idgenerator.constant.IdGeneratorEnum;
import net.lab1024.smartadmin.module.system.department.DepartmentDao;
import net.lab1024.smartadmin.module.system.department.DepartmentResponseCodeConst;
import net.lab1024.smartadmin.module.system.department.domain.dto.DepartmentVO;
import net.lab1024.smartadmin.module.system.department.domain.entity.DepartmentEntity;
import net.lab1024.smartadmin.module.system.employee.EmployeeDao;
import net.lab1024.smartadmin.module.system.employee.domain.bo.EmployeeBO;
import net.lab1024.smartadmin.module.system.employee.domain.dto.CpUserDTO;
import net.lab1024.smartadmin.module.system.employee.domain.dto.EmployeeDTO;
import net.lab1024.smartadmin.module.system.employee.domain.entity.EmployeeEntity;
import net.lab1024.smartadmin.module.system.login.domain.RequestTokenBO;
import net.lab1024.smartadmin.module.system.privilege.service.PrivilegeEmployeeService;
import net.lab1024.smartadmin.module.system.systemconfig.SystemConfigService;
import net.lab1024.smartadmin.module.system.systemconfig.constant.SystemConfigEnum;
import net.lab1024.smartadmin.module.system.systemconfig.domain.dto.SystemConfigDTO;
import net.lab1024.smartadmin.module.weapp.message.MessageDao;
import net.lab1024.smartadmin.module.weapp.message.domain.entity.MessageEntity;
import net.lab1024.smartadmin.module.weapp.orders.OrdersResponseCodeConst;
import net.lab1024.smartadmin.module.weapp.orders.dao.CommentDao;
import net.lab1024.smartadmin.module.weapp.orders.dao.DetailDao;
import net.lab1024.smartadmin.module.weapp.orders.dao.LikesDao;
import net.lab1024.smartadmin.module.weapp.orders.dao.OrdersDao;
import net.lab1024.smartadmin.module.weapp.orders.domain.dto.*;
import net.lab1024.smartadmin.module.weapp.orders.domain.entity.*;
import net.lab1024.smartadmin.module.weapp.orders.domain.vo.*;
import net.lab1024.smartadmin.module.weapp.orderstype.dao.WorkOrderTypeDao;
import net.lab1024.smartadmin.module.weapp.orderstype.domain.entity.WorkOrderTypeEntity;
import net.lab1024.smartadmin.module.weapp.orderstype.domain.vo.WorkOrderTypeVO;
import net.lab1024.smartadmin.module.weapp.users.dao.UsersDao;
import net.lab1024.smartadmin.module.weapp.users.domain.vo.UsersVO;
import net.lab1024.smartadmin.util.SmartPageUtil;
import net.lab1024.smartadmin.util.SmartBeanUtil;
import net.lab1024.smartadmin.util.SmartRequestTokenUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.xmlbeans.impl.soap.DetailEntry;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.lang.reflect.Array;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * [  ]
 *
 * @author wuqian
 * @version 1.0
 * @company 五千
 * @copyright (c)  五千Inc. All rights reserved.
 * @date 2021-03-10 15:12:30
 * @since JDK1.8
 */
@Service
public class OrdersService {

    @Autowired
    private LikesDao likeDao;

    @Autowired
    private DetailDao detailDao;

    @Autowired
    private LikesDao likesDao;

    @Autowired
    private CommentDao commentDao;

    @Autowired
    private OrdersDao ordersDao;

    @Autowired
    private FileService fileService;

    @Autowired
    private IdGeneratorService idGeneratorService;

    @Autowired
    private DepartmentDao departmentDao;

    @Autowired
    private UsersDao usersDao;

    @Autowired
    private WorkOrderTypeDao workOrderTypeDao;

    @Autowired
    private EmployeeDao employeeDao;

    @Autowired
    private PrivilegeEmployeeService privilegeEmployeeService;

    @Autowired
    private SystemConfigService systemConfigService;

    @Autowired
    private MessageDao messageDao;

    @Autowired
    private AddToMessageQueue addToMessageQueue;


    /**
     * 根据id查询
     */
    public ResponseDTO<OrdersVO> getById(Long id) {
        OrdersEntity ordersEntity = ordersDao.selectById(id);
        if (ordersEntity == null) {
            return ResponseDTO.wrap(OrdersResponseCodeConst.ORDERS_NOT_EXISTS);
        }
        OrdersReadLogEntity ordersReadLogEntity = new OrdersReadLogEntity();
        ordersReadLogEntity.setOid(id);
        ordersReadLogEntity.setUid(SmartRequestTokenUtil.getRequestUserId());
        ordersReadLogEntity.setCreateTime(new Date());
        ordersDao.addReadLog(ordersReadLogEntity);

        OrdersVO ordersVO = SmartBeanUtil.copy(ordersEntity,OrdersVO.class);
        if (ordersEntity.getPics() != null && !ordersEntity.getPics().equals("")) {

            List<String> pics1 = Arrays.asList(ordersEntity.getPics().split("\\|"));
            List<OrdersPics> picsList = pics1.stream()
                    .collect(Collectors.mapping((url) -> {
                        OrdersPics ordersPics = new OrdersPics();
                        ordersPics.setUrl(url);
                        return ordersPics;
                    }, Collectors.toList()));

            ordersVO.setPics(picsList);
        }

        ordersVO.setDepartmentObj(departmentDao.selectById(ordersEntity.getDepartmentId()));
        ordersVO.setToUserObj(employeeDao.getEmployeeById(ordersEntity.getToUid()));
        WorkOrderTypeVO workOrderTypeVO = workOrderTypeDao.queryById((long) ordersEntity.getWot());
        ordersVO.setTypeObj(workOrderTypeVO);

        List<OrdersDetailVO> ordersDetailVO = detailDao.selectByOid(ordersEntity.getId());
        for (OrdersDetailVO item:ordersDetailVO) {
            if("".equals(item.getHandOpinionsPicsString()) || item.getHandOpinionsPicsString() == null){
                continue;
            }
            List<String>  sarray = Arrays.asList(item.getHandOpinionsPicsString().split("\\|"));
            List<OrdersPics> opinionPic = new ArrayList<>();
            List<OrdersPics> picsList = sarray.stream()
                    .collect(Collectors.mapping((url) -> {
                        OrdersPics ordersPics = new OrdersPics();
                        ordersPics.setUrl(url);
                        return ordersPics;
                    }, Collectors.toList()));
            item.setOpinionPics(picsList);
        }
        ordersVO.setDetailList(ordersDetailVO);
        ordersVO.setCommentList(commentDao.selectByOid(ordersEntity.getId()));
        ordersVO.setIsLiks(likesDao.selectIsLiks(ordersEntity.getId(),SmartRequestTokenUtil.getRequestUserId()));

        //二级管理员
        if(workOrderTypeVO.getManager2Objs()!=null) {
            ordersVO.setToOpenid2(workOrderTypeVO.getManager2Objs().getUserId());
        }

        ordersVO.setMlist(employeeDao.getEmployeeIdByPostId(16L));
        return ResponseDTO.succData(ordersVO);
    }

    /**
     * 添加评论内容
     * @param commentAddDTO
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public ResponseDTO<String> addComment(CommentAddDTO commentAddDTO){
        OrdersCommentEntity ordersCommentEntity = SmartBeanUtil.copy(commentAddDTO,OrdersCommentEntity.class);
        ordersCommentEntity.setCreateUid(SmartRequestTokenUtil.getRequestUserId());
        ordersCommentEntity.setCreateTime(new Date());
        ordersCommentEntity.setUpdateTime(new Date());
        commentDao.insert(ordersCommentEntity);
        return ResponseDTO.succ();
    }
    /**
     * 获取页面基础数据
     * @author wuqian
     * @date 2021-03-11 15:12:30
     */
    public ResponseDTO<OrdersPageBaseVO> queryPageBase() {
        Long departmentId = SmartRequestTokenUtil.getRequestUser().getEmployeeBO().getDepartmentId();
        DepartmentEntity departmentEntity = departmentDao.selectById(departmentId);
        DepartmentVO departmentVO = SmartBeanUtil.copy(departmentEntity,DepartmentVO.class);
        OrdersPageBaseVO ordersPageBaseVO = new OrdersPageBaseVO();

        List<DepartmentViewVO> departmentViewVOList = new ArrayList<>();
//        for(DepartmentVO item : departmentVOList){
        departmentViewVOList.add(new DepartmentViewVO(departmentVO.getId(),departmentVO.getName()));
//        }
        Map<Long, DepartmentViewVO>  departmentVOHashMap = departmentViewVOList.stream().collect(Collectors.toMap(DepartmentViewVO::getId, Function.identity()));
        ordersPageBaseVO.setDepartmentMap(departmentVOHashMap);
        ordersPageBaseVO.setDepartmentList(departmentViewVOList);

        List<WorkOrderTypeVO> workOrderTypeVOList = workOrderTypeDao.listAll();

        Map<Long,WorkOrderTypeVO>  workOrderTypeVOMap = workOrderTypeVOList.stream().collect(Collectors.toMap(WorkOrderTypeVO::getId, Function.identity()));
        ordersPageBaseVO.setWorkOrderTypeMap(workOrderTypeVOMap);
        ordersPageBaseVO.setWorkOrderTypeList(workOrderTypeVOList);

        Long uid = SmartRequestTokenUtil.getRequestUserId();
        EmployeeDTO employeeDTO = employeeDao.getEmployeeById(uid);
        ordersPageBaseVO.setEmployeeBaseVO(new EmployeeBaseVO(employeeDTO.getActualName(),
                employeeDTO.getPhone(),employeeDTO.getDepartmentId()));

        return ResponseDTO.succData(ordersPageBaseVO);
    }
    /**
     * 分页查询
     * @author wuqian
     * @date 2021-03-10 15:12:30
     */
    public ResponseDTO<PageResultDTO<OrdersVO>> queryByPage(OrdersQueryDTO queryDTO) {
        Page page = SmartPageUtil.convert2QueryPage(queryDTO);

        Long departmentId = SmartRequestTokenUtil.getRequestUser().getEmployeeBO().getDepartmentId();
        Integer isStaff = SmartRequestTokenUtil.getRequestUser().getEmployeeBO().getUserId()!=null?1:0;
        queryDTO.setDepartmentId(departmentId);
        if(!SmartRequestTokenUtil.getRequestUser().getEmployeeBO().getIsSuperman()) {
            queryDTO.setSessionid(SmartRequestTokenUtil.getRequestUserId());
        }
        IPage<OrdersVO> voList = ordersDao.queryByPage(page, queryDTO);
        PageResultDTO<OrdersVO> pageResultDTO = SmartPageUtil.convert2PageResult(voList);
        return ResponseDTO.succData(pageResultDTO);
    }

    /**
     * 添加
     * @author wuqian
     * @date 2021-03-10 15:12:30
     */
    @Transactional(rollbackFor = Exception.class)
    public ResponseDTO<Long> add(OrdersAddDTO addDTO) {
        RequestTokenBO requestTokenBO = SmartRequestTokenUtil.getRequestUser();
        OrdersEntity entity = SmartBeanUtil.copy(addDTO, OrdersEntity.class);
        entity.setFromUid(requestTokenBO.getRequestUserId());
        UsersVO em3 = usersDao.selectByUid(requestTokenBO.getRequestUserId());
        if(em3 != null && em3.getOpenid() != null){
            entity.setFromOpenid(em3.getOpenid());
            //小程序用户
        }else {
            CpUserDTO cpUserDTO = employeeDao.getCpUserByuid(requestTokenBO.getRequestUserId());
            if(cpUserDTO.getUserId() != null){
                //企业微信用户
                entity.setFromOpenid(cpUserDTO.getUserId());
            }
        }

        entity.setCreateTime(new Date());
        entity.setUpdateTime(new Date());

        String no = idGeneratorService.generate(IdGeneratorEnum.WORK_ORDER); // 编码生成
        entity.setNo(no);//编码
        //
        WorkOrderTypeVO workOrderTypeVO = workOrderTypeDao.queryById(Long.valueOf(addDTO.getWot()));
        entity.setTitle("服务工单-"+workOrderTypeVO.getLabel()+"-"+no);

        entity.setPics(StringUtils.join(addDTO.getPics(),"|"));

        //修改当前人 姓名，手机号
        EmployeeEntity entity1 = new EmployeeEntity();
        entity1.setId(requestTokenBO.getRequestUserId());
        entity1.setActualName(addDTO.getActualName());
        entity1.setPhone(addDTO.getMobile());
        employeeDao.updateById(entity1);//更新 联系人- 电话

        SmartRequestTokenUtil.getRequestUser();


        WorkOrderTypeEntity workOrderTypeEntity = workOrderTypeDao.selectById(entity.getWot());
        entity.setToUid(workOrderTypeEntity.getManager());
        //获取类型管理员信息
//        EmployeeEntity em2 = usersDao.selectByUid(workOrderTypeEntity.getManager());
//        if(em2 != null && em2.getOpenid() != null)
//            entity.setToOpenid(em2.getOpenid());
//        else if(em2 != null && em2.getEmployeeObj() != null)
//            entity.setToOpenid(em2.getEmployeeObj().getUserId());
//
//        ordersDao.insertAndGetId(entity);
//
//        //添加推送消息
//        addToMessageQueue.addMinMessage(entity,em2,0);

        return ResponseDTO.succData(entity.getId());
    }

    /**
     * 处理
     * @param handleDTO
     * @return
     * @author wuqian
     * @date 2021-03-14 15:12:30
     */
    @Transactional(rollbackFor = Exception.class)
    public ResponseDTO<String> handle(OrdersHandleDTO handleDTO){
//        //判断 当前用户是否 是管理员
        Long uid = SmartRequestTokenUtil.getRequestUserId();
//        Boolean isSuperman = privilegeEmployeeService.isSuperman(uid);
//        if(!isSuperman){
//            return ResponseDTO.wrap(OrdersResponseCodeConst.HAND_NOT_AUTH);
//        }
        OrdersEntity entity = new OrdersEntity();
        entity.setId(handleDTO.getId());
        entity.setStatue(handleDTO.getStatue());
        entity.setUpdateTime(new Date());

        if(handleDTO.getStatue() == 1){
            //接收工单
            String levelDesc = handleDTO.getLevel();//获取处理工单等级
            if(levelDesc == null){
                return ResponseDTO.wrapMsg(ResponseCodeConst.ERROR_PARAM,"缺省工单等级，系统报错");
            }
            SystemConfigDTO systemConfigDTO = systemConfigService.getCacheByKey(SystemConfigEnum.Key.selectByKey(levelDesc));
            Integer levelValue = Integer.valueOf(systemConfigDTO.getConfigValue());

            if(levelValue<=0){
                levelValue = 30;
            }
            Date waitTime = new Date();
            Calendar   calendar = new GregorianCalendar();
            calendar.setTime(waitTime);
            calendar.add(calendar.DATE,levelValue); //把日期往后增加一天,整数  往后推,负数往前移动
            waitTime = calendar.getTime(); //这个时间就是日期往后推一天的结果
            entity.setWaitTime(handleDTO.getWaitTime()==null?waitTime:handleDTO.getWaitTime());
            entity.setLevelDesc(systemConfigDTO.getConfigName());
        }
        if(handleDTO.getStatue() == 2){
            //处理完成
            entity.setCompleteTime(new Date());
        }
        ordersDao.updateById(entity);
        if(handleDTO.getStatue() == 2 && handleDTO.getOpinion() != null){
            //处理完成
            OrdersDetailEntity ed = new OrdersDetailEntity();
            ed.setOid(handleDTO.getId());
            ed.setHandOpinions(handleDTO.getOpinion());

            List<String> picss = new ArrayList<>();
            for(OrdersPics item : handleDTO.getOpinionPics()){
                picss.add(item.getUrl());
            }

            ed.setHandOpinionsPicsString(StringUtils.join(picss,"|"));
            ed.setHandUser(uid);
            ed.setCreateTime(new Date());
            ed.setUpdateTime(new Date());
            detailDao.insertVE(ed);
        }


        //添加处理状态改变
//        OrdersEntity en2 = ordersDao.selectById(entity.getId());
//        UsersVO em2 = usersDao.selectByUid(en2.getFromUid());
//        OrdersEntity entity2 = ordersDao.selectById(entity.getId());
//        addToMessageQueue.addMinMessage(entity2,em2,handleDTO.getStatue());

        return ResponseDTO.succ();
    }
    /**
     * 编辑
     * @author wuqian
     * @date 2021-03-10 15:12:30
     */
    @Transactional(rollbackFor = Exception.class)
    public ResponseDTO<Long> update(OrdersUpdateDTO updateDTO) {
        OrdersEntity entity = SmartBeanUtil.copy(updateDTO, OrdersEntity.class);
        entity.setUpdateTime(new Date());
        if(updateDTO.getPics()!=null) {
            entity.setPics(StringUtils.join(updateDTO.getPics(), "|"));
        }

        //修改当前人 姓名，手机号
        if(entity.getFromUid() != null) {
            EmployeeEntity entity1 = new EmployeeEntity();
            entity1.setId(entity.getFromUid());
            entity1.setActualName(entity.getActualName());
            entity1.setPhone(entity.getMobile());
            employeeDao.updateById(entity1);//更新 联系人- 电话
        }

        ordersDao.updateById(entity);
        return ResponseDTO.succData(entity.getId());
    }

    /**
     * 删除
     * @author wuqian
     * @date 2021-03-10 15:12:30
     */
    @Transactional(rollbackFor = Exception.class)
    public ResponseDTO<String> deleteByIds(List<Long> idList) {
        ordersDao.deleteByIdList(idList);
        return ResponseDTO.succ();
    }

    /**
     * 查询全部导出对象
     * @author wuqian
     * @date 2021-03-10 15:12:30
     */
    public List<OrdersExcelVO> queryAllExportData(OrdersQueryDTO queryDTO) {
        return ordersDao.queryAllExportData( queryDTO);
    }

    /**
     * 批量查询导出对象
     * @author wuqian
     * @date 2021-03-10 15:12:30
     */
    public List<OrdersExcelVO> queryBatchExportData(List<Long> idList) {
        return ordersDao.queryBatchExportData(idList);
    }

    /**
     * 点赞处理
     * @param id
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public ResponseDTO<String> upLike(Long id) {

        OrdersLikeEntity ordersLikeEntity = new OrdersLikeEntity();
        ordersLikeEntity.setCreateUid(SmartRequestTokenUtil.getRequestUserId());
        ordersLikeEntity.setOid(id);

        ordersLikeEntity.setCreateTime(new Date());
        ordersLikeEntity.setUpdateTime(new Date());
        likeDao.addLike(ordersLikeEntity);
        return ResponseDTO.succ();
    }

    /**
     * 工单切换 一级管理人
     * @param handDTO
     * @return
     */
    public ResponseDTO<String> changeOrderPeroperHand(OrdersHandleDTO handDTO) {
        EmployeeDTO employeeDTO =  employeeDao.getEmployeeById(handDTO.getHangePeoperid());
        //判断 当前用户是否 是管理员
        Long uid = SmartRequestTokenUtil.getRequestUserId();
//        Boolean isSuperman = privilegeEmployeeService.isSuperman(uid);
//        if(!isSuperman){
//            return ResponseDTO.wrap(OrdersResponseCodeConst.HAND_NOT_AUTH);
//        }
        OrdersEntity entity = new OrdersEntity();
        entity.setId(handDTO.getId());
        entity.setToUid(employeeDTO.getId());
        entity.setToOpenid(employeeDTO.getUserId());
        entity.setUpdateTime(new Date());

        ordersDao.updateById(entity);


        OrdersEntity ordersEntity = ordersDao.selectById(handDTO.getId());
        //添加推送消息
        //获取类型管理员信息
//        UsersVO em2 = usersDao.selectByUid(handDTO.getHangePeoperid());
//        if(em2 != null && em2.getOpenid() != null)
//            ordersEntity.setToOpenid(em2.getOpenid());
//        else if(em2 != null && em2.getEmployeeObj() != null)
//            ordersEntity.setToOpenid(em2.getEmployeeObj().getUserId());
//        addToMessageQueue.addMinMessage(ordersEntity,em2,0);


        return ResponseDTO.succ();
    }
}